package com.controller;

import com.pojo.Books;
import com.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BooksController {

    @Autowired
    @Qualifier("BooksServiceImpl")
    private BooksService booksService;


    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = booksService.selAllBooks();

        model.addAttribute("list", books);

        return "allBook";
    }

    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "addBook";
    }

    @RequestMapping("addBook")
    public String addBook(Books books){
        booksService.addBooks(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("delBook")
    public String deleteBook(int id){
        booksService.delBooks(id);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(int id, Model model){
        Books books = booksService.selBooks(id);
        model.addAttribute("books", books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        booksService.updBooks(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/selBookByName")
    public String selBookByName(String bookName, Model model){
        List<Books> books = booksService.selBookByName(bookName);

        if (books == null || books.size() == 0){
            books = booksService.selAllBooks();
            model.addAttribute("msg", "未查到");
        }

        model.addAttribute("list", books);

        return "allBook";
    }
}
